import Header from "../components/Header";
import Menu from "../components/Menu";
import Footer from "../components/Footer";
import { Outlet, useLocation } from "react-router-dom";
import NProgress from "nprogress";
import request from "../utils/request";
import Cookies from 'js-cookie';
import React, { useState,useEffect } from "react";


export default function MainLayout() {
  const location = useLocation();
  const [iframeUrl, setIframeUrl] = useState(null);


  useEffect(() => {
    NProgress.start();
    // 模拟异步加载，实际可根据页面加载情况调整
    const timer = setTimeout(() => {
      NProgress.done();
    }, 400);
    return () => clearTimeout(timer);
  }, [location.pathname]);


    const apiBase = import.meta.env.VITE_API_BASE;
// 用于 axios 或 fetch 请求
  console.log("API Base URL:", apiBase);

  const handleLogout = () => {

    // 处理登出逻辑
    request.post(apiBase+"/logout")
      .then(response => {
        if (response.data && response.data.code === 200) {
          // 登出成功后清除本地存储和 Cookie
          localStorage.removeItem("menus");
          localStorage.removeItem("isLoggedIn");
          localStorage.removeItem("authButtons");
          // Cookies.remove('authToken', { path: '/' });
          // 重定向到登录页面
          window.location.href = "/login";
        } else {
          console.error("登出失败:", response.data.message);
        }
      })
      .catch(error => {
        console.error("登出请求失败:", error);
      });

    // //请求后端登出接口（如果有的话）
    // // 这里可以添加实际的登出请求逻辑
    // // 清除 isLoggedIn 和菜单按钮数据
    // localStorage.removeItem("menus");
    // localStorage.removeItem("isLoggedIn");
    // localStorage.removeItem("authButtons");

    // // 清除 authToken Cookie
    // Cookies.remove('authToken', { path: '/' });
    // // 重定向到登录页面
    // window.location.href = "/login";
  };


  

  return (
    <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh" }}>
      <Header onLogout={handleLogout} />
      <div style={{ flex: 1, display: "flex", minHeight: 0 }}>
        {/* 传递 setIframeUrl 给 Menu */}
        <Menu onOpenExternal={setIframeUrl} onRoute={() => setIframeUrl(null)} />
        <main style={{ flex: 1, padding: 16, background: "#fafbfc" }}>
          {iframeUrl ? (
            <iframe src={iframeUrl} style={{ width: "100%", height: "100vh", border: "none" }} />
          ) : (
            <Outlet />
          )}
        </main>
      </div>
      <Footer />
    </div>
  );
}